package com.example.restatr.Atcivity.Movie;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.bumptech.glide.Glide;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.Movie.Bean.MovieFilmBean;
import com.example.restatr.Atcivity.Movie.Bean.MovieOrderListBean;
import com.example.restatr.Atcivity.Movie.Bean.MovieSeatBean;
import com.example.restatr.Atcivity.Movie.Bean.MovieTheatreTimesBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MovieOrderAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private ImageView cover;
    private TextView movieName;
    private TextView ticketNum;
    private TextView price;
    private TextView date;
    private TextView cinema;
    private TextView movieHall;
    private RelativeLayout ddbhRL;
    private TextView ddbh;
    private TextView zffs;
    private RelativeLayout zzc;
    private TextView money;
    private RelativeLayout js;
    private CardView payCard;
    private LinearLayout BtnLL;
    private List<MovieSeatBean.DataBean> 座位信息;
    private MovieTheatreTimesBean.RowsBean 影院影片场次信息;
    private PopupWindow popupWindow;
    private List<MovieOrderListBean.RowsBean> orderListBean;
    private MovieFilmBean.RowsBean 电影信息;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.movie_order_layout);

        toolbar = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        cover = findViewById(R.id.cover);
        movieName = findViewById(R.id.movieName);
        ticketNum = findViewById(R.id.ticketNum);
        price = findViewById(R.id.price);
        date = findViewById(R.id.date);
        cinema = findViewById(R.id.cinema);
        movieHall = findViewById(R.id.movieHall);
        ddbhRL = findViewById(R.id.ddbh_RL);
        ddbh = findViewById(R.id.ddbh);
        zffs = findViewById(R.id.zffs);
        zzc = findViewById(R.id.zzc);
        money = findViewById(R.id.money);
        js = findViewById(R.id.js);
        payCard = findViewById(R.id.payCard);
        BtnLL = findViewById(R.id.Btn_LL);

        Tools.SetBarTitle(toolbar, barTitle, "电影订单", search, this,false);
        座位信息 = new Gson().fromJson(getIntent().getStringExtra("座位信息"), new TypeToken<List<MovieSeatBean.DataBean>>() {
        }.getType());
        影院影片场次信息 = new Gson().fromJson(getIntent().getStringExtra("影院影片场次信息"), new TypeToken<MovieTheatreTimesBean.RowsBean>() {
        }.getType());
        电影信息 = new Gson().fromJson(getIntent().getStringExtra("电影信息"), new TypeToken<MovieFilmBean.RowsBean>() {
        }.getType());
        Glide.with(this)
                .load(Tools.ip + 电影信息.getCover())
                .into(cover);
        movieName.setText(影院影片场次信息.getMovieName());
        ticketNum.setText(座位信息.size() + "张");
        price.setText("单价¥ " + 影院影片场次信息.getPrice());
        date.setText(影院影片场次信息.getPlayDate() + " " + 影院影片场次信息.getStartTime() + "-" + 影院影片场次信息.getEndTime());
        cinema.setText(getIntent().getStringExtra("影院名称"));
        String seat = "";
        for (int i = 0; i < 座位信息.size(); i++) {
            seat += 座位信息.get(i).getRow() + "排" + 座位信息.get(i).getCol() + "座 ";
        }
        movieHall.setText(影院影片场次信息.getRoomName() + " " + seat);
        money.setText("¥" + getIntent().getIntExtra("总价", 0));
    }

    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.Zf_LL:
                //创建popupWindow
                View inflate = getLayoutInflater().inflate(R.layout.popupwindow_layout, null);
                TextView pz = inflate.findViewById(R.id.pz);
                TextView xc = inflate.findViewById(R.id.xc);
                pz.setText("极速支付");
                xc.setText("普通支付");
                popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setAnimationStyle(R.style.anim_photo_select);
                popupWindow.showAtLocation(toolbar, Gravity.BOTTOM, 0, 0);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        zzc.setVisibility(View.GONE);
                    }
                });
                zzc.setVisibility(View.VISIBLE);
                break;
            case R.id.button:
                CreateOrder();
                break;
            case R.id.delete:
                DeleteOrder();
                break;
            case R.id.comment:
                Intent intent = new Intent(MovieOrderAt.this, MovieInfoAt.class);
                intent.putExtra("Intent", "Comment");
                intent.putExtra("电影信息", getIntent().getStringExtra("电影信息"));
                startActivity(intent);
                break;
        }
    }

    //popupWindow按钮点击事件
    public void ppWindowClick(View view) {
        switch (view.getId()) {
            case R.id.pz:
                zffs.setText("极速支付");
                break;
            case R.id.xc:
                zffs.setText("普通支付");
                break;
        }
        popupWindow.dismiss();
    }

    //创建订单
    private void CreateOrder() {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("playDate", 影院影片场次信息.getPlayDate());
                jsonObject.put("startTime", 影院影片场次信息.getStartTime());
                jsonObject.put("endTime", 影院影片场次信息.getEndTime());
                jsonObject.put("theaterId", 影院影片场次信息.getTheaterId());
                jsonObject.put("movieId", 影院影片场次信息.getMovieId());
                jsonObject.put("roomId", 影院影片场次信息.getRoomId());
                jsonObject.put("timesId", 影院影片场次信息.getId());
                jsonObject.put("price", 影院影片场次信息.getPrice());
                JSONArray orderItemArray = new JSONArray();
                JSONObject orderItems = new JSONObject();
                for (int i = 0; i < 座位信息.size(); i++) {
                    orderItems.put("price", 影院影片场次信息.getPrice());
                    orderItems.put("seatCol", 座位信息.get(i).getCol());
                    orderItems.put("seatId", 座位信息.get(i).getId());
                    orderItems.put("seatRow", 座位信息.get(i).getRow());
                    orderItemArray.put(orderItems);
                }
                jsonObject.put("orderItems", orderItemArray);
                String post = Tools.Post("/prod-api/api/movie/ticket", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(post);
                int code = jx.getInt("code");
                String msg = jx.getString("msg");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        PayOrder();
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //支付订单
    private void PayOrder() {
        new Thread(() -> {
            try {
                //获取订单列表，获取列表最后一位，获取订单号
                String getOrderList = Tools.Get("/prod-api/api/movie/ticket/order/list", MainActivity.sp.getString("token", ""));
                MovieOrderListBean movieOrderListBean = new Gson().fromJson(getOrderList, MovieOrderListBean.class);
                orderListBean = new ArrayList<>();
                orderListBean.addAll(movieOrderListBean.getRows());
                //订单支付
                String pay = Tools.Get("/prod-api/api/movie/ticket/order/pay/" + orderListBean.get(orderListBean.size() - 1).getId(), MainActivity.sp.getString("token", ""));
                JSONObject jx = new JSONObject(pay);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        ddbhRL.setVisibility(View.VISIBLE);
                        BtnLL.setVisibility(View.VISIBLE);
                        payCard.setVisibility(View.GONE);
                        js.setVisibility(View.GONE);
                        ddbh.setText(orderListBean.get(orderListBean.size() - 1).getOrderNo());
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //删除订单
    private void DeleteOrder() {
        new Thread(() -> {
            try {
                String token = Tools.Delete("/prod-api/api/movie/ticket/order/" + orderListBean.get(orderListBean.size() - 1).getId(), MainActivity.sp.getString("token", ""));
                JSONObject jx = new JSONObject(token);
                int code = jx.getInt("code");
                String msg = jx.getString("msg");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        finish();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }


}
